#include "mesh.h"
#include "vector3.h"
#include <vector>

using namespace krryn::scene;
using namespace krryn::math;

void mesh::update_aabb(){
	for(size_t i = 0; i < m_IndexCount; i++){
		m_Aabb.expand(m_Vertices[m_Indices[i]].m_Position);
	}
}

void mesh::make_counter_clockwise(){
	for(size_t i = 0; i < m_IndexCount; i += 3){
		std::swap(m_Indices[i], m_Indices[i + 2]);
	}
}

void mesh::update_normals(){
	std::vector<vector3f> *l_NormalBuffer = new std::vector<vector3f>[m_VertexCount];

	for(size_t i = 0; i < m_IndexCount; i += 3){
		vector3f p1 = m_Vertices[m_Indices[i+0]].m_Position;
		vector3f p2 = m_Vertices[m_Indices[i+1]].m_Position;
		vector3f p3 = m_Vertices[m_Indices[i+2]].m_Position;

		vector3f v1 = p2 - p1;
		vector3f v2 = p3 - p1;
		vector3f l_Normal = v1.cross(v2);

		l_NormalBuffer[m_Indices[i+0]].push_back(l_Normal);
		l_NormalBuffer[m_Indices[i+1]].push_back(l_Normal);
		l_NormalBuffer[m_Indices[i+2]].push_back(l_Normal);
	}

	for(size_t i = 0; i < m_VertexCount; i++){
		for(size_t j = 0; j < l_NormalBuffer[i].size(); j++){
			m_Vertices[i].m_Normal += l_NormalBuffer[i][j];
		}

		m_Vertices[i].m_Normal = m_Vertices[i].m_Normal.normalize();
	}

	delete[] l_NormalBuffer;
}